package com.linuxrm.countdown.gaokao
import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import java.text.SimpleDateFormat
import java.util.*
import java.io.File
object CountdownLogic {
    const val PREFS_KEY = "gaokao_target_datetime"
    val dateFormat: SimpleDateFormat
        get() = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
    fun getTargetDate(context: Context): Calendar {
        val prefs = context.getSharedPreferences("MainActivity", Context.MODE_PRIVATE)
        val savedTimestamp = prefs.getLong(PREFS_KEY, -1)
        return Calendar.getInstance().apply {
            if (savedTimestamp != -1L) {
                timeInMillis = savedTimestamp
            } else {
                set(Calendar.getInstance().get(Calendar.YEAR), Calendar.JUNE, 7, 9, 0, 0)
            }
        }
    }
    fun getCurrentDateTimeString(): String {
        return dateFormat.format(Date(System.currentTimeMillis()))
    }
    fun getCountdownText(targetDate: Calendar): SpannableString {
        val currentTime = System.currentTimeMillis()
        val diffMillis = targetDate.timeInMillis - currentTime
        val hours = diffMillis / (60 * 60 * 1000.0)
        val days = hours / 24.0
          // 计算小时数
        val daysStr = String.format(Locale.CHINA, "%.7f", days)
        val hoursStr = String.format(Locale.CHINA, "%.4f", hours)
        val parts = daysStr.split(".")
        val integerPart = parts[0]
        val decimalPart = if (parts.size > 1) ".${parts[1]}" else ""
        val fullText = "高考 $integerPart $decimalPart 天\n=$hoursStr 小时"
        val spannable = SpannableString(fullText)
        val startIndex = 3
        val endIndex = 3 + integerPart.length
        spannable.setSpan(
            RelativeSizeSpan(3f),
            startIndex, endIndex,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannable.setSpan(
            StyleSpan(android.graphics.Typeface.BOLD),
            startIndex, endIndex,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        if (decimalPart.isNotEmpty()) {
            spannable.setSpan(
                ForegroundColorSpan(Color.RED),
                endIndex, endIndex + decimalPart.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        val hoursStartIndex = fullText.indexOf('=') + 1
        val hoursEndIndex = fullText.indexOf(' ', hoursStartIndex)
        spannable.setSpan(
            ForegroundColorSpan(Color.RED),
            hoursStartIndex, hoursEndIndex,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannable
    }
    fun isDaemonRunning(context: Context): Boolean {
        val lockFile = File(context.filesDir, "widget_daemon.pid")
        if (!lockFile.exists()) return false
        return try {
            val pid = lockFile.readText().trim().toInt()
            val process = Runtime.getRuntime().exec(arrayOf("su", "-c", "ps -p $pid"))
            val exitCode = process.waitFor()
            exitCode == 0
        } catch (e: Exception) {
            false
        }
    }
}
